package org.db.ui;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import org.db.dao.GleisDAO;

public class GleisDefinitionTableModel extends AbstractTableModel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5226832106117421437L;

	private List<GleisDAO> data = new ArrayList<GleisDAO>();

	private DecimalFormat format1 = new DecimalFormat("0.000");

	private DecimalFormat format2 = new DecimalFormat("0");

	Class<?>[] types = new Class[]{java.lang.Integer.class,
			java.lang.String.class, java.lang.Double.class,
			java.lang.Double.class

	};

	@Override
	public int getColumnCount() {
		return 4;
	}

	@Override
	public int getRowCount() {
		return data.size();
	}

	@Override
	public Object getValueAt(int row, int column) {
		switch (column) {
			case 0 :
				return data.get(row).getGleisID();
			case 1 :
				return data.get(row).getBezeichnung();
			case 2 :
				return format1.format(data.get(row).getAnfangsStation());
			case 3 :
				return format2.format(data.get(row).getAbstandKmLinie());
			default :
				return "";
		}
	}

	@Override
	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		GleisDAO dao = data.get(rowIndex);
		switch (columnIndex) {
			case 2 :
				updateAnfangstationValues((Double) value);
				fireTableDataChanged();
				break;
			case 3 :
				dao.setAbstandKmLinie((Double) value);
				fireTableCellUpdated(rowIndex, columnIndex);
				break;

		}

	}

	@Override
	public String getColumnName(int column) {
		switch (column) {
			case 0 :
				return "Gleis- ID";
			case 1 :
				return "Bezeichnung";
			case 2 :
				return "Anfangsstation";
			case 3 :
				return "Abstand KM- Linie";
			default :
				return "";
		}
	}

	@Override
	public boolean isCellEditable(int row, int column) {
		return false;
	}

	@Override
	public Class<?> getColumnClass(int columnIndex) {
		return types[columnIndex];
	}

	public void addGleisElement(GleisDAO dao) {
		data.add(dao);
		fireTableDataChanged();
	}

	public void addGleisElemente(List<GleisDAO> daos) {
		data.addAll(daos);
		fireTableDataChanged();
	}

	public List<GleisDAO> getGleisElemente() {
		return data;
	}

	public boolean isEmpty() {
		return data.isEmpty();
	}

	private void updateAnfangstationValues(double anfangsStation) {
		for (GleisDAO dao : data) {
			dao.setAnfangsStation(anfangsStation);
		}
	}

	public void removeGleisElement(GleisDAO dao) {
		data.remove(dao);
		fireTableDataChanged();
	}

	public GleisDAO removeGleisElement(int rowIndex) {
		GleisDAO removedDAO = data.remove(rowIndex);
		fireTableDataChanged();
		return removedDAO;
	}

	public GleisDAO getElementAtRow(int row) {
		if (row < data.size()) {
			return data.get(row);
		}
		return null;
	}

	public void refresh() {
		fireTableDataChanged();
	}

}
